package cn.wenhaha.app.log.service.job;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.wenhaha.common.db.bean.SysSyncError;
import cn.wenhaha.common.db.bean.SysSyncReport;
import cn.wenhaha.job.Job;
import cn.wenhaha.job.WynJobBean;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;

/**
 * 清空日志表
 * 每周一 凌晨 运行
 * --------
 *
 * @author ：wyndem
 * @Date ：Created in 2023-01-07 18:44
 */
@Job(corn = "0 0 0 ? * MON", jobId = 3L)
public class CleanLogReportJob extends WynJobBean {

    @Resource
    private SysSyncError syncErrorDao;

    @Resource
    private SysSyncReport syncReport;

    /**
     * <p>
     * 1. 清空上周的天、周
     * 2. 清空上月数据
     * 3. 清空上季数据
     * 3. 清空去年数据
     * </p>
     *
     * @Author: Wyndem
     * @DateTime: 2023-01-07 18:46
     */
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        cleanErrorJob();
        cleanReportJob();
    }


    /**
     * <p>
     * 清空错误日志
     * </p>
     *
     * @Author: Wyndem
     * @DateTime: 2023-01-27 12:33
     */
    private void cleanErrorJob() {
        DateTime dateTime = DateUtil.beginOfDay(new Date());
        syncErrorDao.deleteByLTDate(dateTime.toJdkDate());
    }


    /**
     * <p>
     *    清空日志统计数据
     * </p>
     * @Author: Wyndem
     * @DateTime: 2023-01-27 13:07
     */
    private void cleanReportJob() {
        Date date = new Date();
        int row = 0;
        // 先从年开始删除，直到删除了数据后，停止
        for (int i = 4; i > 0 && row == 0; i--) {
            row = syncReport.deleteByLTDate(getDate(i,date),i);
        }

    }


    /**
     * <p>
     *    计算时间
     * </p>
     * @param type  4 年 3季 2月 1 周
     * @Author: Wyndem
     * @DateTime: 2023-01-27 13:05
     */
    private Date getDate(Integer type, Date date) {
        switch (type) {
            case 4:
                return DateUtil.beginOfYear(date);
            case 3:
                return DateUtil.beginOfQuarter(date);
            case 2:
                return DateUtil.beginOfMonth(date);
            case 1:
                return DateUtil.beginOfWeek(date);
            default:
                return date;
        }
    }

}
